//
//  OSSUploadApi.swift
//  MT
//
//  Created by M on 2019/12/24.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import MTCategory

import RxSwift
import RxDataSources
import Moya
import Result

@objc
enum UploadStatus: Int {
    /// 无状态
    case none = 0
    /// 准备上传
    case ready
    /// 正在上传
    case uploading
    /// 上传成功
    case finished
    /// 上传失败
    case fail
}

enum UploadApi {
    
    case upload(_ image: UIImage)
    
    case uploadVideo(_ url: URL)
    
}

extension UploadApi: MTTargetType {
    
    public var headers: [String : String]? {
        guard let accessToken = UserCenter.default.auth?.token else { return nil }
        return ["Access-Token": accessToken]
    }
    
    /// The method used for parameter encoding.
    var parameterEncoding: ParameterEncoding {
        return URLEncoding.default
    }
    
    /// Provides stub data for use in testing.
    public var sampleData: Data {
        return "".data(using: String.Encoding.utf8)!
    }
    
    /// 基路径
    public var baseURL: URL {
        return URL(string: AuthServerBaseUrl)!
    }
    
    /// 路径
    public var path: String {
        switch self {
        case .upload:
            return "/file/upload"
        case .uploadVideo:
            return "/file/upload"
        }
    }
    
    /// 请求方法
    public var method: Moya.Method {
        switch self {
        default:        return .post
        }
    }
    
    /// 参数
    var params: [String: Any]? {
        switch self {
            
        default: return nil
        }
    }
    
    /// The type of HTTP task to be performed.
    public var task: Task {
        switch self {
        case let .upload(image):
            guard let data = image.compress() else { return .uploadCompositeMultipart([], urlParameters: [:]) }
            let fileName = DateManager.currentTimeString() + "\(arc4random_uniform(10000) + 10000)" + ".png"
            let fileData = MultipartFormData(provider: .data(data), name: "file", fileName: fileName, mimeType: "image/png")
            return .uploadCompositeMultipart([fileData], urlParameters: [:])
            
        case let .uploadVideo(url):
            guard let data = try? Data(contentsOf: url) else { return .uploadCompositeMultipart([], urlParameters: [:]) }
            let fileName = DateManager.currentTimeString() + "\(arc4random_uniform(10000) + 10000)" + ".mov"
            let fileData = MultipartFormData(provider: .data(data), name: "file", fileName: fileName, mimeType: "image/png")
            return .uploadCompositeMultipart([fileData], urlParameters: [:])
        }
    }
    
    /// Whether or not to perform Alamofire validation. Defaults to `false`.
    public var validate: Bool {
        return false
    }
    
}
